<?php

namespace App\Http\Controllers\Api;

use App\Coupon;
use App\UserCoupon;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class UserCouponController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $coupons = UserCoupon::latest()->where('user_id', Auth::id())->limit(30)->get();
        return $coupons;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $coupon = Coupon::where('id', $request->coupon_id)->where('status', 1)->first();
        if (!$coupon) {
            return response(['优惠券不存在'], 404);
        }
        if ($coupon->sent_num >= $coupon->total) {
            return response(['下手慢了，优惠券已被抢光'], 400);
        }
        $data = [
            'coupon_id' => $coupon->id,
            'user_id' => Auth::id(),
            'mini_consumption' => $coupon->mini_consumption,
            'money' => $coupon->money,
            'start_use_at' => $coupon->type == 'FIXED' ? $coupon->start_use_at : Carbon::now(),
            'end_use_at' => $coupon->type == 'FIXED' ? $coupon->end_use_at : Carbon::now()->addDays($coupon->time_scope),
            'use_scope' => $coupon->use_scope,
            'use_scope_id' => $coupon->use_scope_id,
        ];
        $userCoupon = UserCoupon::create($data);
        $coupon->increment('sent_num');
        return $userCoupon;
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\UserCoupon  $userCoupon
     * @return \Illuminate\Http\Response
     */
    public function show(UserCoupon $userCoupon)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\UserCoupon  $userCoupon
     * @return \Illuminate\Http\Response
     */
    public function edit(UserCoupon $userCoupon)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\UserCoupon  $userCoupon
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, UserCoupon $userCoupon)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\UserCoupon  $userCoupon
     * @return \Illuminate\Http\Response
     */
    public function destroy(UserCoupon $userCoupon)
    {
        //
    }
}
